require([
    'jquery',
    'module/util',
    'global',
    'underscore',
    'holder',
    'module/handlebars',
    'jquery.chosen',
    'icheck',
    'plupload',
	'requirejs/domready!'],
function($, util, g, _, Holder, handlebars) {
	var uploaders = {};
	
	$('#edit-pd-modal form select').chosen({
		width: "100%",
		no_results_text: "没有发现记录匹配"
	});
	
	$('#model-select').change(function(e){
		$('#model-features-select').val('');
		render_feature_list($(this).val());
	});
    
    var render_feature_list = function(modelId, values){
    	if(!modelId) return;
    	$('#model-features-select').empty();
    	$.when($.getJSON(g.context+'/admin/vehicle_model/'+modelId+'/features'), 
				handlebars.getTemplate('model-features-select'))
			.done(function(defer, tmpl){
				var d = defer[0].data;
				if(d && _.isEmpty(d)){
					d = null;
				}
				var html = tmpl({vmfMap: d});
				$('#model-features-select')
					.append(html)
					.val(values)
					.trigger('chosen:updated');
			});
    };
    
    var old_features = [];
    $('#model-features-select').change(function(e){
    	var $that = $(this);
    	var new_features = $(this).val();
    	var difs = _.difference(new_features, old_features);
    	var inters = _.intersection(new_features, old_features);
    	var dif_cs = [], old_handled = [];
    	_.each(difs, function(dif){
    		var c = $that.find('option[value="'+dif+'"]').data('category');
    		dif_cs.push(c);
    	});
    	_.each(inters, function(old){
    		var c = $that.find('option[value="'+old+'"]').data('category');
    		if(!_.contains(dif_cs, c)){
    			old_handled.push(old);
    		}
    	});
    	old_features = new_features = _.union(difs, old_handled);
    	$(this).val(new_features).trigger('chosen:updated');
    });
	
	$('#edit-pd-modal form input[type="checkbox"]').iCheck({
	    checkboxClass: 'icheckbox_flat-blue',
	    radioClass: 'iradio_flat-blue',
	    increaseArea: '20%'
	  });
	
	var attach_uploader = function(btn_id){
		var uploader = new plupload.Uploader({
		    browse_button: btn_id,
		    url: g.context + '/upload',
		    multi_selection: false,
		    unique_names: true,
		    filters: {
		        mime_types : [
		            { title : "Image files", extensions : "jpg,gif,png" }
				],
		        max_file_size: '3072kb'
		    }
		});
		uploader.init();
		uploader.bind('FilesAdded', function(up, files) {
			var $b = $(up.settings.browse_button);
			var $fc = $b.parents('.img-box').find('.file-container');
			var html = '';
		    plupload.each(files, function(file) {
		        html += '<li class="file-label" id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></li>';
		    });
		    $fc.find('> .file-label').remove();
		    $fc.prepend(html);
		    $fc.removeClass('hide');
		    uploader.start();
		});
		uploader.bind('UploadProgress', function(up, file) {
			var $b = $(up.settings.browse_button);
			$b.parents('.img-box').find('.progress-bar').width(file.percent + '%');
		});
		uploader.bind('FileUploaded', function(up, qu, res){
			var $b = $(up.settings.browse_button);
			if(res.status == 200){
				$b.parents('.img-box')
					.find('input[type="hidden"]').val(res.response);
				$b.parents('.img-box')
					.find('.file-container').addClass('hide');
				$b.parents('.img-box')
					.find('> img')
						.removeClass('default')
						.attr('src', g.context+res.response);
			}
		});
		uploaders[btn_id] = uploader;
	};
	
	_.each(['intro-pic-btn','param-pic-btn','dismounting-pic-btn','merging-pic-btn',,'mobile-pic-btn'], 
			function(id){
				attach_uploader(id);
			});
	
	$('#edit-pd-modal .btn-upload')
	$('#edit-pd-modal').on('show.bs.modal', function(){
		var obj = $(this).data('obj');
		if(!obj){
			$(this).find('.modal-header .action').text('添加');
		}else{
			$(this).find('.modal-header .action').text('编辑');
		}
		obj = obj || {};
		$(this).find('form input, form select').each(function(){
			if($(this).attr('name')){
				$(this).val(obj[[$(this).attr('name')]]);
			}
		});
		$(this).find('.img-box > img').each(function(){
			if(obj[$(this).data('prop')]){
				$(this).attr('src', g.context + obj[$(this).data('prop')]).removeClass('default');
			}else{
				$(this).attr('src', '').addClass('default');
			}
		});
		$(this).find('form select').trigger("chosen:updated");
		
		// update features select
		render_feature_list($('#model-select').val(),obj['featureIds']);
	}).on('hidden.bs.modal', function(){
		$('#model-features-select').val('').empty();
	}).on('click', '.btn-primary', function(){
		var dto = {};
		$('#edit-pd-modal').find('form input, form select').each(function(){
			if($(this).attr('name')){
				dto[$(this).attr('name')] = $(this).val();
			}
		});
		$.ajax({
		  type: 'post',
		  dataType: 'json',
		  url: g.context+ '/admin/product',
		  data: JSON.stringify(dto),
		  contentType: 'application/json; charset=utf-8',
		  headers:{
			  'x-form-id': 'edit-pd-modal'
		  }
	    }).done(function(result){
	    	if(result.code == 'ACK'){
		    	$('#edit-pd-modal').modal('hide');
		    	$(window).trigger('ok.xt.modal', ['#edit-pd-modal']);
	    	}
	    });
	});
});